package cn.itsource.config.mq;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 作用：声明队列、交换机以及他们的绑定关系
 * @author Jason
 * @date 2022-09-04 23:37
 */
@Configuration
public class RabbitMQConfig {

    //声明队列-短信队列
    @Bean
    public Queue smsQueue(){
        return new Queue("sms_queue", true, false, false, null);
    }

    //声明队列-邮件队列
    @Bean
    public Queue emailQueue(){
        return new Queue("email_queue", true, false, false, null);
    }

    //声明交换机
    @Bean
    public Exchange exchange(){
        return ExchangeBuilder.topicExchange("hrm_exchange").build();
    }

    //声明交换机和队列的绑定
    @Bean
    public Binding binding1(){
        return BindingBuilder.bind(smsQueue()).to(exchange()).with("#.sms").noargs();
    }

    //声明交换机和队列的绑定
    @Bean
    public Binding binding2(){
        return BindingBuilder.bind(emailQueue()).to(exchange()).with("#.email").noargs();
    }

    //初始化RabbitAdmin对象
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        // 只有设置为 true，spring 才会加载 RabbitAdmin 这个类
        rabbitAdmin.setAutoStartup(true);

        //下面设置目的：项目启动时，就创建交换机和队列
        //创建交换机
        rabbitAdmin.declareExchange(exchange());
        //创建对列
        rabbitAdmin.declareQueue(smsQueue());
        rabbitAdmin.declareQueue(emailQueue());

        return rabbitAdmin;
    }
}
